/**
 * 
 */
package com.hk.Mgr.web.controller.product;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;

import com.hk.Mgr.web.controller.UserCtr;
import com.hk.Mgr.web.controller.remoteCall.ActivityService;
import com.hk.Mgr.web.message.order.QueryProductListReq;

import com.hk.app.utils.*;
import com.hk.commons.*;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.order.OrderInfo;
import com.hk.commons.vo.CheckInfo;
import com.hk.commons.vo.JsonResult;
import com.hk.commons.vo.ProductInfoRes;
import com.hk.service.ISafety;
import com.hk.service.product.*;
import com.hk.service.sys.ISysUserRoles;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.order.ProductInfoReq;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.entity.product.ProductInfo;
import com.hk.service.kyc.IAgreement;
import com.hk.service.order.IOrderInfo;

/**
 * @author psx 产品信息实现类
 */
@Controller
@RequestMapping(value = BaseCtrl.MgrRootPath + "/ProductInfoCtrl")
public class ProductInfoCtrl extends BaseCtrl {

	private Logger logger = LoggerFactory.getLogger(ProductInfoCtrl.class);

	@Autowired
	private IProductRouteInfo productRouteService;

	@Autowired
	private IProductInfo productInfoService;

	@Autowired
	private IOrderInfo orderService;

	@Autowired
	private IProductParInfo proParService;

	@Autowired
	private IAgreement aggService;

	@Autowired
	private ICompany companyService;

    @Autowired
    private UserCtr userCtrl;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private ISysUserRoles userRoleService;

    @Autowired
    private SendMsgCilent sendMsgCilent;

    @Autowired
    private ISafety safetyService;

	@Autowired
    private AmqpTemplate rabbitTemplate;

    @Autowired
    ActivityService activityService;

    @Autowired
    private IAgreementToProduct iAgreementToProduct;
	
    public static final String POUNDAGE_QUEUE = "poundage_queue";

    /**
     * @param
     * @Title: getProductInfoById
     * @Description: 根据id获取系统模块信息
     */
    @ResponseBody
    @RequestMapping(value = "/getProductInfoById", method = RequestMethod.POST)
    public ResponseBase<ProductInfoRes> getProductInfoById(
            @RequestBody ProductInfoReq req) {
        ResponseBase<ProductInfoRes> resp = new ResponseBase<ProductInfoRes>();
        try {
            if (req == null || req.getId() == null) {
                resp.setResultCode(StatusCode.PARAM_ERROR.key());
                resp.setMsg("参数不对：id is null！");
                return resp;
            }

            ProductInfoRes singleResp = productInfoService.getProductInfoResById(req.getId());

            resp.setResultCode(StatusCode.SUCCESS.key());
            resp.setResult(singleResp);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resp.setMsg("操作异常，请重试");
            resp.setResultCode(StatusCode.EXCEPTION.key());
        }
        return resp;
    }

    /**
     * @param
     * @Title: getProductInfoList
     * @Description: 分页获取系统模块
     */
    @ResponseBody
    @RequestMapping(value = "/getProductInfoList", method = RequestMethod.POST)
    public ResponseBase<List<ProductInfoRes>> getProductInfoList(
            @RequestBody ProductInfoReq req) {
        ResponseBase<List<ProductInfoRes>> resp = new ResponseBase<List<ProductInfoRes>>();

        if(req == null){
            resp.setResultCode(StatusCode.PARAM_ERROR.key());
            resp.setMsg("参数错误");
            return resp;
        }
        /*
        logger.info("/getProductInfoList 输入参数为：prodTopType = {},publishType={}, proTerm={}, isTest={},proStatus ={}, name={}",
                req.getProdTopType(), req.getPublishType(), req.getProTerm(), req.getIsTest(), req.getProStatus(), req.getName());
        */
        List<ProductInfoRes> respList = new ArrayList<ProductInfoRes>();

        HqlFilter hqlFilter = new HqlFilter();

        hqlFilter.addSql(" where 1=1 " );

        // 发行方式
        if (StringUtils.isNotEmpty(req.getPublishType())) {
            hqlFilter.addEQFilter("publishType", req.getPublishType());
        }
        // 投资期限
        if (req.getProTerm() != null) {
            hqlFilter.addEQFilter("proTerm", req.getProTerm());
        }

        // 产品名称
        if (StringUtils.isNotEmpty(req.getName())) {
            hqlFilter.addLKFilter("name", req.getName());
        }

        // 产品上下架状态
        if (req.getProStatus() != null) {
            hqlFilter.addEQFilter("proStatus", req.getProStatus());
        }

        // 产品一级类型
        if (req.getProdTopType() != null) {
            hqlFilter.addEQFilter("prodTopType", req.getProdTopType());
        }

        // 产品二级类型
        if (req.getProdType() != null) {//2
            hqlFilter.addEQFilter("prodType", req.getProdType());
        }

        //是否为测试产品
        if (req.getIsTest() != null) {
            hqlFilter.addEQFilter("isTest", req.getIsTest());
        }


        //如果有父标Id， 则只显示父标，否则只显示子标
        if (req.getParId() == null){
            hqlFilter.addSql(" and isParent = 1 " );
            hqlFilter.addSort("name");

        }else{
            hqlFilter.addSql(" and isParent = 0  and parId = " +  req.getParId());
            // 升序排列
            hqlFilter.addSort("startSaleTime");
            hqlFilter.addOrder("desc");
        }

        logger.info("hqlFilter = " + hqlFilter.getWhereHql());
        try {
            List<ProductInfo> productInfoList = productInfoService
                    .findByFilter(hqlFilter, req.getCurPage(),
                            req.getPageSize());
            if (req.getPageSize() > 50) {

                ProductInfoRes singleResp = new ProductInfoRes();

                respList.add(singleResp);

                Long total = productInfoService.countByFilter(hqlFilter);
                resp.setSize(total);
                resp.setResultCode(StatusCode.SUCCESS.key());
                resp.setResult(respList);
            } else {
                // 根据模块id查询资源
                if (productInfoList != null && !productInfoList.isEmpty()) {
                    ProductInfoRes singleResp = null;
                    for (ProductInfo productInfo : productInfoList) {
                        singleResp = productInfoService.getProductInfoResById(productInfo.getId());
                        respList.add(singleResp);
                    }
                }
                Long total = productInfoService.countByFilter(hqlFilter);
                resp.setSize(total);
                resp.setResultCode(StatusCode.SUCCESS.key());
                resp.setResult(respList);
            }


        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resp.setMsg("操作异常，请重试");
            resp.setResultCode(StatusCode.EXCEPTION.key());
        }
        return resp;
    }

    /**
     * @param
     * @Title: getProductInfoList
     * @Description: 获取父标列表
     */
    @ResponseBody
    @RequestMapping(value = "/getParProdInfoList", method = RequestMethod.POST)
    public ResponseBase<List<ProductInfo>> getParProdInfoList(
            @RequestBody ProductInfoReq req) {
        ResponseBase<List<ProductInfo>> resp = new ResponseBase<List<ProductInfo>>();

        if(req == null){
            resp.setResultCode(StatusCode.PARAM_ERROR.key());
            resp.setMsg("参数错误");
            return resp;
        }
        logger.info("/getParProdInfoList 输入参数为：prodTopType = {}", req.getProdTopType() );

        HqlFilter hqlFilter = new HqlFilter();

        hqlFilter.addSql(" where 1=1 and isParent = 1 " );

        // 产品一级类型
        if (req.getProdTopType() != null) {
            hqlFilter.addEQFilter("prodTopType", req.getProdTopType());
        }

        hqlFilter.addSort("name");
        logger.info("hqlFilter = " + hqlFilter.getWhereHql());

        try {
            List<ProductInfo> productInfoList = productInfoService.findByFilter(hqlFilter );
            resp.setSize(productInfoList.size());
            resp.setResultCode(StatusCode.SUCCESS.key());
            resp.setResult(productInfoList);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resp.setMsg("操作异常，请重试");
            resp.setResultCode(StatusCode.EXCEPTION.key());
        }
        return resp;
    }

    /**
     * @param
     * @Title: getProductInfoList
     * @Description: 获取火柴加息产品列表
     */
    @ResponseBody
    @RequestMapping(value = "/getHCAddRateProdList", method = RequestMethod.GET)
    public ResponseBase<List<ProductInfo>> getHCAddRateProdList() {
        ResponseBase<List<ProductInfo>> resp = new ResponseBase<List<ProductInfo>>();

        HqlFilter hqlFilter = new HqlFilter();

        hqlFilter.addSql(" where 1=1 and issuerId = 3 and isParent = 0 ");
        hqlFilter.addLKFilter("name", "加息");
        hqlFilter.addSort("name");

        logger.info("hqlFilter = " + hqlFilter.getWhereHql());

        List<ProductInfo> productInfoList = productInfoService.findByFilter(hqlFilter );
        resp.setSize(productInfoList.size());
        resp.setResultCode(StatusCode.SUCCESS.key());
        resp.setResult(productInfoList);

        return resp;
    }

    /**
     * @param
     * @Title: setSaleTime 自动上下架
     * @Description: TODO
     */
    @ResponseBody
    @RequestMapping(value = "/setSaleTime", method = RequestMethod.POST)
    public ResponseBase<ProductInfoRes> setSaleTime(
            @RequestBody ProductInfoReq req) {
        ResponseBase<ProductInfoRes> resp = new ResponseBase<ProductInfoRes>();

        try {

            if (resp == null || req.getId() == null || StringHelper.isEmpty(req.getStartSaleTime())||  StringHelper.isEmpty(req.getEndSaleTime())) {
                resp.setResultCode(StatusCode.ERROR.key());
                resp.setMsg("参数错误，请重试！");
                return resp;
            }

            Long prodId = req.getId();
            ProductInfo model = productInfoService.findById(prodId);
            if (model == null) {
                resp.setResultCode(StatusCode.ERROR.key());
                resp.setMsg("该产品不存在，请重试！");
                return resp;
            }

            String startSaleTimeStr = req.getStartSaleTime();
            String endSaleTimeStr = req.getEndSaleTime();

            String saleOutTimeStr = req.getSaleOutTime();
            String chgBuyTypeTimeStr = req.getChgBuyTypeTime();

            Timestamp startSaleTime = Timestamp.valueOf(startSaleTimeStr) ;
            Timestamp endSaleTime = Timestamp.valueOf(endSaleTimeStr);

            logger.info("set sale time id={}, startSaleTime={}, endSaleTime={}", req.getId(), startSaleTime, endSaleTime);
            if (model != null) {
                model.setStartSaleTime(startSaleTime);
                model.setEndSaleTime(endSaleTime);
                if(StringHelper.isNotEmpty(saleOutTimeStr)){
                    Timestamp saleOutTime = Timestamp.valueOf(saleOutTimeStr);
                    model.setSaleOutTime(saleOutTime);
                }else{
                    model.setSaleOutTime(null);
                }

                if(StringHelper.isNotEmpty(chgBuyTypeTimeStr)){
                    Timestamp chgBuyTypeTime = Timestamp.valueOf(chgBuyTypeTimeStr);
                    model.setChgBuyTypeTime(chgBuyTypeTime);
                    long currentTime = System.currentTimeMillis();
                    if(currentTime<chgBuyTypeTime.getTime()){
                        model.setWaitSale(1);
                    }else{
                        model.setWaitSale(0);
                    }
                }else{
                    model.setChgBuyTypeTime(null);
                    model.setWaitSale(0);
                }

                productInfoService.update(model);

                ProductInfoRes  res = productInfoService.getProductInfoResById(req.getId());
                resp.setResult(res);
                resp.setResultCode(StatusCode.SUCCESS.key());
            }

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resp.setMsg("操作异常，请重试");
            resp.setResultCode(StatusCode.EXCEPTION.key());
        }

        return resp;
    }

    /**
     * @param
     * @Title: saveProductInfo
     * @Description: TODO
     */
    @ResponseBody
    @RequestMapping(value = "/saveProductInfo", method = RequestMethod.POST)
    public ResponseBase<ProductInfo> saveProductInfo(
            @RequestBody ProductInfoReq req) {

        ResponseBase<ProductInfo> resp = new ResponseBase<ProductInfo>();

        try {
            ProductInfo model = new ProductInfo();
            ReqToModelHelper.copyReqValueToModel(req, model);

            if (StringUtils.isNotBlank(req.getIntroduce())) {
                byte[] introduce = req.getIntroduce().getBytes("UTF-8");
                model.setIntroduce(introduce);
            } else {
                model.setIntroduce(null);
            }
            if (StringUtils.isNotBlank(req.getIncome())) {
                byte[] income = req.getIncome().getBytes("UTF-8");
                model.setIncome(income);
            } else {
                model.setIncome(null);
            }
            if (StringUtils.isNotBlank(req.getRiskctrl())) {
                byte[] riskctrl = req.getRiskctrl().getBytes("UTF-8");
                model.setRiskctrl(riskctrl);
            } else {
                model.setRiskctrl(null);
            }

            if (StringUtils.isNotBlank(req.getSignflow())) {
                byte[] signflow = req.getSignflow().getBytes("UTF-8");
                model.setSignFlow(signflow);
            } else {
                model.setSignFlow(null);
            }

            if (StringUtils.isNotBlank(req.getProductDescription())) {
                model.setClaimRecommendInfo(req.getProductDescription());
            } else {
                model.setClaimRecommendInfo(null);
            }

            // 设置产品的默认属性
            // 设置产品的已募集金额为 0
            model.setYraiseAccount(new BigDecimal(0));
            // 设置产品的剩余额度为募集总量
            model.setSraiseAccount(model.getFinancingAccount());
            // 设置产品的已预约金额为 0
            model.setBespeakAccount(new BigDecimal(0));

            // 设置产品上架状态为未上架
            model.setProStatus(ConstantProduct.PRODUCT_RELEASE_STATE_FALSE);

            // 设置产品热销属性为非热销
            model.setHotSale(ConstantProduct.PRODUCT_HOT_SELLING_FALSE);

            //一个产品对应多份合同，为了兼容旧版本，把第一份放到原字段
            model.setContractId(req.getAgreements().get(0));

            //初始化版本号
            model.setVersion(0);

            // 根据路由表保存产品信息到相应的表中
            Long newProductId = productRouteService.addProduct(model);

            //产品与合同的关系保存到中间表
            iAgreementToProduct.updateOrSave(req.getAgreements(),newProductId);

            if (newProductId > 0L) {
                resp.setResultCode(StatusCode.SUCCESS.key());
                resp.setMsg("添加成功");

                resp.setResult(model);
            } else {
                resp.setMsg("产品编码或者名称已存在,保存失败！产品名称为：" + model.getName());
                resp.setResultCode(StatusCode.EXCEPTION.key());
            }

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resp.setMsg("操作异常，请重试");
            resp.setResultCode(StatusCode.EXCEPTION.key());
        }

        return resp;
    }

    /**
     * @param
     * @Title: updateProductInfo
     * @Description: TODO
     */
    @ResponseBody
    @RequestMapping(value = "/updateProductInfo", method = RequestMethod.POST)
    public ResponseBase<ProductInfo> updateProductInfo(
            @RequestBody ProductInfoReq req) {
        ResponseBase<ProductInfo> resp = new ResponseBase<ProductInfo>();
        try {
            if (req == null || req.getId() == null) {
                resp.setResultCode(StatusCode.PARAM_ERROR.key());
                resp.setMsg("参数不对：id is null！");
                return resp;
            }
            ProductInfo model = productInfoService.findById(req.getId());
            req.setWaitSale(null); //修改产品时这个字段并不会改变，但是由于默认值是0，所以造成每次修改都把0更新进去
			/*
			logger.info(
					"产品信息  autoStartDiv={}, 修改后的 startDiv={}, 修改前的 startDiv={}",
					model.getAutStartDiv(), req.getStartDiv(),
					model.getStartDiv());
			
			
			// 如果产品不是自动起息，并且未开始计息，则更改产品相关的订单
			if (model.getAutStartDiv() == ConstantProduct.PRO_NO_AUTO_START_DIV
					&& req.getStartDiv() == ConstantProduct.PRO_START_DIV
					&& model.getStartDiv() == ConstantProduct.PRO_NOT_START_DIV) {
				logger.info(
						"产品开始计息 productId={}, tradeTime={}, dividendTime={}",
						model.getId(), req.getProDividStartDate(),
						req.getProDividendDate());
				if (req.getProDividStartDate() != null
						&& req.getProDividendDate() != null) {
					Timestamp tradeTime = req.getProDividStartDate();
					Timestamp dividendTime = req.getProDividendDate();
					orderService.startDiv(model.getId(), tradeTime,
							dividendTime);
				}
			}
			*/
            ReqToModelHelper.copyReqValueToModel(req, model);

            /*由于不会把空值复制过来，所以清空时间时会更新不到数据库，要特别处理*/
            if(StringUtils.isBlank(req.getClearDate())){
                model.setClearDate(null);
            }
            model.setListingNumber(req.getListingNumber());

            if(req.getBuyType() != null){
                model.setBuyType(req.getBuyType());
            }

            if(req.getAddRateProduct01()!= null){
                model.setAddRateProduct01(req.getAddRateProduct01());
            }

            if(req.getAddRateProduct02()!= null){
                model.setAddRateProduct02(req.getAddRateProduct02());
            }

            if(req.getLimitNum() != null){
                logger.info("req.getLimitNum() = {}", req.getLimitNum());
                model.setLimitNum(req.getLimitNum());
            }else{
                logger.info("req.getLimitNum() is null");
                model.setLimitNum(null);
            }



            if(req.getSaleType() != null){
                model.setSaleType(req.getSaleType());
            }

            if(req.getLimitAmount() != null){
                model.setLimitAmount(req.getLimitAmount());
            }else{
                model.setLimitAmount(null);
            }

            if (StringHelper.isNotEmpty(req.getCreditorPhoneNum())) {
                model.setCreditorPhoneNum(req.getCreditorPhoneNum().trim());
            }
            if (StringUtils.isNotBlank(req.getIntroduce())) {
                byte[] introduce = req.getIntroduce().getBytes("UTF-8");
                model.setIntroduce(introduce);
            } else {
                model.setIntroduce(null);
            }
            if (StringUtils.isNotBlank(req.getProductDescription())) {
                model.setClaimRecommendInfo(req.getProductDescription());
            }
            if (StringUtils.isNotBlank(req.getIncome())) {
                byte[] income = req.getIncome().getBytes("UTF-8");
                model.setIncome(income);
            } else {
                model.setIncome(null);
            }
            if (StringUtils.isNotBlank(req.getRiskctrl())) {
                byte[] riskctrl = req.getRiskctrl().getBytes("UTF-8");
                model.setRiskctrl(riskctrl);
            } else {
                model.setRiskctrl(null);
            }

            if (StringUtils.isNotBlank(req.getSignflow())) {
                byte[] signflow = req.getSignflow().getBytes("UTF-8");
                model.setSignFlow(signflow);
            } else {
                model.setSignFlow(null);
            }

            if(req.getDiscount() == 0){
                model.setDiscountEndDate(null);
                model.setDiscountRate(null);
            }else{
                if( req.getDiscountEndDate() != null){
                    model.setDiscountEndDate(req.getDiscountEndDate());

                }

                if(StringHelper.isNotEmpty(req.getDiscountRate())){
                    model.setDiscountRate(req.getDiscountRate());

                }
            }
            model.setUpdateTime(System.currentTimeMillis());

            //一个产品对应多份合同，为了兼容旧版本，把第一份放到原字段
            model.setContractId(req.getAgreements().get(0));
            //产品与合同的关系保存到中间表
            iAgreementToProduct.updateOrSave(req.getAgreements(),req.getId());

            // 根据路由表，对产品进行更新
            Boolean result = productRouteService.updateProduct(model);
            System.out.println("result = " + result);
            if (result) {
                resp.setResult(model);
                resp.setResultCode(StatusCode.SUCCESS.key());
                resp.setMsg("修改成功");
            } else {
                resp.setMsg("产品编码或者名称已存在,修改失败！产品名称为：" + model.getName());
                resp.setResultCode(StatusCode.EXCEPTION.key());
            }

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resp.setMsg("操作异常，请重试");
            resp.setResultCode(StatusCode.EXCEPTION.key());
        }
        return resp;
    }

    /**
     * 产品起标划拨
     *
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/transfer", method = RequestMethod.POST)
    public ResponseBase<ProductInfo> transfer(
            @RequestBody ProductInfoReq req) {



        ResponseBase<ProductInfo> resp = new ResponseBase<ProductInfo>();

        try {
            if (req == null
                    || req.getId() == null
                    || req.getStartDiv() == null
                    || req.getProDividStartDate() == null
                    || req.getProDividendDate() == null
                    || req.getClearDate() == null) {
                resp.setResultCode(StatusCode.PARAM_ERROR.key());
                resp.setMsg("参数不对 部分参数为空！");
                return resp;
            }

            logger.info(
                    "进入产品起标划拨接口 产品信息 productId ={},  autoStartDiv={}, 起息日 ={}, 还本付息日 ={}",
                    req.getId(), req.getStartDiv(), req.getProDividStartDate(), req.getProDividendDate());

            //起息日
            Timestamp tradeTime = req.getProDividStartDate();

            //还本付息日
            Timestamp dividendTime = req.getProDividendDate();

            Long productId = req.getId();
            ProductInfo model = productInfoService.findById(productId);

            if (model == null) {
                resp.setResultCode(StatusCode.PARAM_ERROR.key());
                resp.setMsg("产品不存在productId = " + productId);
                return resp;
            }


            if(model.getProStatus() == ConstantProduct.PRODUCT_RELEASE_STATE_FALSE){
                resp.setResultCode(StatusCode.ERROR.key());
                resp.setMsg("产品未上架，不允许划拨，此次划拨失败！");
                return resp;
            }


            if(model.getProStatus() == ConstantProduct.PRODUCT_RELEASE_STATE_TRUE) {
                if (model.getSaleOut() == 0) {
                    resp.setResultCode(StatusCode.ERROR.key());
                    resp.setMsg("产品未满标，不允许划拨，此次划拨失败！");
                    return resp;
                }
            }


            logger.info(
                    "产品信息  autoStartDiv={}, 修改后的 startDiv={}, 修改前的 startDiv={}",
                    model.getAutStartDiv(), req.getStartDiv(),
                    model.getStartDiv());

            // 如果产品不是自动起息，并且未开始计息，则更改产品相关的订单

            if (model.getAutStartDiv() == ConstantProduct.PRO_NO_AUTO_START_DIV
                    && req.getStartDiv() == ConstantProduct.PRO_START_DIV
                    && model.getStartDiv() == ConstantProduct.PRO_NOT_START_DIV) {
                logger.info(
                        "产品开始计息 productId={}, tradeTime={}, dividendTime={}",
                        model.getId(), req.getProDividStartDate(),
                        req.getProDividendDate());

                orderService.startDiv(model.getId(), tradeTime, dividendTime);

            }

            //更新产品信息
            model.setStartDiv(req.getStartDiv());
            model.setProDividStartDate(req.getProDividStartDate());
            model.setProDividendDate(req.getProDividendDate());
            model.setClearDate(Timestamp.valueOf(req.getClearDate()));
            productInfoService.update(model);

            resp.setResult(productInfoService.findById(productId));
            resp.setResultCode(StatusCode.SUCCESS.key());
            resp.setMsg("修改成功");

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resp.setMsg("操作异常，请重试");
            resp.setResultCode(StatusCode.EXCEPTION.key());
        }
        return resp;
    }
	
	/**
	 * htt产品回款划拨
	 * @param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/httPayback", method = RequestMethod.POST)
	public ResponseBase<ProductInfo> httPayback(//"mgr/ProductInfoCtrl/httPayback?productId89943456733196&userId=77290832527171"
			@RequestBody  ProductInfoReq req ) {

        ResponseBase<ProductInfo> resp = new ResponseBase<ProductInfo>();


        if(req == null || req.getProductId() == null ||
                StringHelper.isEmpty(req.getCode01()) || StringHelper.isEmpty(req.getCode02())){
            resp.setResultCode(ResultCode.PARAM_LACK.getCode());
            resp.setMsg("参数错误，部分参数为空。");
            return resp;
        }

        if(req.getUserId() == null){
            resp.setResultCode(ResultCode.PARAM_LACK.getCode());
            resp.setMsg("登录超时，请重新登录后尝试。");
            return resp;
        }




        Long productId = req.getProductId();
        Long userId = req.getUserId();
        String code01 = req.getCode01();
        String code02 = req.getCode02();

		try {
            Long longProductId = Long.valueOf(productId);






            CheckInfo checkInfo = safetyService.checkErrorNum(longProductId);
            if(checkInfo.getResult() == false){
                resp.setResultCode(StatusCode.PARAM_ERROR.key());
                resp.setMsg(checkInfo.getResultMsg());
                logger.info("进入产品回款划拨接口，检查短信验证码输入错误次数 productId ={}",productId);
                return resp;
            }
            ProductInfo product = productInfoService.findById(longProductId);

            checkInfo =  safetyService.checkPayBackMsgCode(code01, code02);

            if(checkInfo.getResult() == false){
                resp.setResultCode(StatusCode.PARAM_ERROR.key());
                resp.setMsg(checkInfo.getResultMsg());
                safetyService.updErrorNum(product);
                logger.info("进入产品回款划拨接口，短信验证码校验错误 productId ={}",productId);
                return resp;
            }

            logger.info("进入产品回款划拨接口，短信验证码校验成功。");

			if(product == null ){
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("产品不存在 productId = " +  productId);				
				logger.info("进入产品回款划拨接口，产品不存在 productId ={}",longProductId);				
				return resp;
			}	
			if(product.getStartDiv()== null
					||product.getStartDiv()==0){//未起标
					resp.setResultCode(StatusCode.ERROR.key());
					resp.setMsg("产品未起标，不能回款!");				
					logger.info("产品未起标，不能回款 productId ={}",longProductId);				
					return resp;				
			}
			if(product.getPayBackStatus() !=null  && product.getPayBackStatus() == ConstantProduct.PRODUCT_PAYBACK_STATUS_TRUE){//已回款
				resp.setResultCode(StatusCode.ERROR.key());
				resp.setMsg("产品已回款，禁止再次回款!");				
				logger.info("产品已回款，禁止再次回款 productId ={}",longProductId);				
				return resp;				
			}

			if(product.getCreditorType()!=null && product.getCreditorType()==1 && req.getRepayPoundage() == null){
                resp.setResultCode(StatusCode.ERROR.key());
                resp.setMsg("企业回款必须填写手续费!");
                logger.info("企业回款失败 productId ={}",longProductId);
                return resp;
            }

			String creditorPhoneNum=product.getCreditorPhoneNum();//债权人手机号码
			BigDecimal allRaiseAmount=product.getFinancingAccount();//融资金额

			if(StringHelper.isEmpty(creditorPhoneNum)){
				resp.setResultCode(StatusCode.ERROR.key());
				resp.setMsg("债权人手机号为空，不能回款 !");				
				logger.info("债权人手机号为空，不能回款  productId ={}",longProductId);				
				return resp;
			}
			if(allRaiseAmount==null){
				resp.setResultCode(StatusCode.ERROR.key());
				resp.setMsg("产品募集额度为空，不能回款! " );				
				logger.info("产品募集额度为空，不能回款! productId ={}",longProductId);				
				return resp;
			}		
			
			String sql="select count(1) from t_order_info where productId="+productId +" and confirmStatus in ("+ConstantOrderStatus.CONFIRM_STATUS__NO_CONFIRM+","+ConstantOrderStatus.CONFIRM_STATUS_FALSE+")";
			Integer sumCardsCount = jdbcTemplate.queryForObject(sql,
					null, Integer.class);
			if(sumCardsCount!=null&&sumCardsCount.intValue()>0){
				resp.setResultCode(StatusCode.ERROR.key());
				resp.setMsg("产品存在未起标划拨的订单，不能回款!" );
				logger.info("产品存在未起标划拨的订单，不能回款! productId ={}",longProductId);
				return resp;
			}

            /*企业回款要自定义手续费*/
			if(product.getCreditorType() != null && product.getCreditorType()==1){
                product.setRepayPoundage(req.getRepayPoundage());
            }
            productInfoService.update(product);

            productInfoService.addLogRecord(Long.valueOf(productId), Long.valueOf(userId));

			rabbitTemplate.convertAndSend(POUNDAGE_QUEUE, productId);
			resp.setResult(productInfoService.findById(longProductId));
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("开始回款,请等待");
		} catch (Exception ex) {
			logger.info("后台系统回款划拨异常！ productId ={}",productId);
			logger.error("后台系统回款划拨异常！", ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

    /**
     * 产品回款划拨
     *
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getProdOrderInfo", method = RequestMethod.POST)
    public ResponseBase<Map<String, Object>> getProdOrderInfo(@RequestBody ProductInfoReq req) {

        ResponseBase<Map<String, Object>> resp = new ResponseBase<Map<String, Object>>();

        try {


            if (req == null || req.getId() == null) {
                resp.setResultCode(StatusCode.PARAM_ERROR.key());
                resp.setMsg("参数不对 部分参数为空！停止回款！");
                return resp;
            }

            Long productId = req.getId();
            ProductInfo product = productInfoService.findById(productId);

            CheckInfo checkInfo = safetyService.checkErrorNum(productId);
            if(checkInfo.getResult() == false){
                resp.setResultCode(StatusCode.PARAM_ERROR.key());
                resp.setMsg(checkInfo.getResultMsg());
                logger.info("进入产品回款划拨接口，检查短信验证码输入错误次数 productId ={}",productId);
                return resp;
            }




            if(product == null){
                resp.setResultCode(StatusCode.PARAM_ERROR.key());
                resp.setMsg("参数不对该产品不存在！停止回款");
                return resp;
            }

            if(product.getProDividendDate() == null){
                resp.setResultCode(StatusCode.PARAM_ERROR.key());
                resp.setMsg("产品还本付息日为空！停止回款");
                return resp;
            }


            if(product == null ){
                resp.setResultCode(StatusCode.PARAM_ERROR.key());
                resp.setMsg("产品不存在 productId = " +  productId);
                logger.info("进入产品回款划拨接口，产品不存在 productId ={}",productId);
                return resp;
            }

            if(product.getStartDiv()== null
                    ||product.getStartDiv()==0){//未起标
                resp.setResultCode(StatusCode.ERROR.key());
                resp.setMsg("产品未起标，不能回款!");
                logger.info("产品未起标，不能回款 productId ={}",productId);
                return resp;
            }
            if(product.getPayBackStatus() !=null  && product.getPayBackStatus() == ConstantProduct.PRODUCT_PAYBACK_STATUS_TRUE){//已回款
                resp.setResultCode(StatusCode.ERROR.key());
                resp.setMsg("产品已回款，禁止再次回款!");
                logger.info("产品已回款，禁止再次回款 productId ={}",productId);
                return resp;
            }
            String creditorPhoneNum=product.getCreditorPhoneNum();//债权人手机号码
            BigDecimal allRaiseAmount=product.getFinancingAccount();//融资金额

            if(StringHelper.isEmpty(creditorPhoneNum)){
                resp.setResultCode(StatusCode.ERROR.key());
                resp.setMsg("债权人手机号为空，不能回款 !");
                logger.info("债权人手机号为空，不能回款  productId ={}",productId);
                return resp;
            }
            if(allRaiseAmount==null){
                resp.setResultCode(StatusCode.ERROR.key());
                resp.setMsg("产品募集额度为空，不能回款! " );
                logger.info("产品募集额度为空，不能回款! productId ={}",productId);
                return resp;
            }

            String sql="select count(1) from t_order_info where productId="+productId +" and confirmStatus in ("+ConstantOrderStatus.CONFIRM_STATUS__NO_CONFIRM+","+ConstantOrderStatus.CONFIRM_STATUS_FALSE+")";
            Integer sumCardsCount = jdbcTemplate.queryForObject(sql,
                    null, Integer.class);
            if(sumCardsCount!=null&&sumCardsCount.intValue()>0){
                resp.setResultCode(StatusCode.ERROR.key());
                resp.setMsg("产品存在未起标划拨的订单，不能回款!" );
                logger.info("产品存在未起标划拨的订单，不能回款! productId ={}",productId);
                return resp;
            }

            Map<String, Object> orderMag = new HashMap<>();

            sql = "select sum(`successAmount`) as  totalSuccessAmount, sum(`dividend`) as orderDiv , sum(`payBackAmt`) as orderPayBackAmount, count(*) as  orderSize  from `t_order_info`  where `paymentId` = 11111111 and `payStatus`  = 2 and `confirmStatus`  = 2 and productId = ? ";

            Map<String, Object> qryMap=jdbcTemplate.queryForMap(sql,new Object [] {productId});

            BigDecimal orderPayAmount =qryMap.get("totalSuccessAmount")== null?new BigDecimal(0.00):(BigDecimal)qryMap.get("totalSuccessAmount");

            BigDecimal orderDiv = qryMap.get("orderDiv")==null?new BigDecimal(0.00):(BigDecimal)qryMap.get("orderDiv");

            BigDecimal orderPayBackAmount = qryMap.get("orderPayBackAmount")==null?new BigDecimal(0.00): (BigDecimal)qryMap.get("orderPayBackAmount");

            Long orderSize = qryMap.get("orderSize") == null?0:(Long)qryMap.get("orderSize");



            if(orderSize != null && orderSize == 0){
                resp.setResultCode(StatusCode.ERROR.key());
                resp.setMsg("产品没有待回款待订单，不能回款!" );
                logger.info("产品没有待回款待订单，不能回款! productId ={}",productId);
                return resp;
            }

            logger.info("所有检查均成功");



            orderMag.put("prodName", product.getName());

            orderMag.put("orderSize", orderSize);

            orderMag.put("orderPayAmount", orderPayAmount);

            orderMag.put("orderDiv", orderDiv);

            orderMag.put("orderPayBackAmount", orderPayBackAmount);

            orderMag.put("payBackStatus", product.getPayBackStatus());

            orderMag.put("orderPayBackTime", product.getProDividendDate().getTime());

            resp.setResult(orderMag);
            resp.setResultCode(StatusCode.SUCCESS.key());
            resp.setMsg("获取消息成功");


        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resp.setMsg("操作异常，请重试");
            resp.setResultCode(StatusCode.EXCEPTION.key());
        }
        return resp;
    }




    /**
     * 产品回款划拨
     *
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getPayBackCode", method = RequestMethod.POST)
    public ResponseBase<Boolean> getPayBackCode(@RequestBody ProductInfoReq req) {

        ResponseBase<Boolean> resp = new ResponseBase<Boolean>();

        try {
            if (req == null || req.getProductId() == null) {
                resp.setResultCode(StatusCode.PARAM_ERROR.key());
                resp.setMsg("参数不对 部分参数为空！停止回款！");
                return resp;
            }

            Long productId = req.getProductId();

            ProductInfo product = productInfoService.findById(productId);

            CheckInfo checkInfo = safetyService.sendPayBackMsgCode(product.getName());

            if(checkInfo.getResult() == false) {
                resp.setResultCode(StatusCode.ERROR.key());
                resp.setMsg(checkInfo.getResultMsg());
                logger.info("产品回款划拨，发送短信验证码失败! productId ={}", productId);
                return resp;
            }

            resp.setResult(true);
            resp.setResultCode(StatusCode.SUCCESS.key());
            resp.setMsg("发送短信验证码成功");
            return  resp;
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resp.setMsg("操作异常，请重试");
            resp.setResultCode(StatusCode.EXCEPTION.key());
        }
        return resp;
    }






    /**
     * @param
     * @Title: updateProdStatus
     * @Description: TODO
     */
    @ResponseBody
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    public ResponseBase<ProductInfo> updateStatus(
            @RequestBody ProductInfoReq req) {
        ResponseBase<ProductInfo> resp = new ResponseBase<ProductInfo>();


        try {
            if (req == null || req.getId() == null) {
                resp.setResultCode(StatusCode.PARAM_ERROR.key());
                resp.setMsg("参数不对：id is null！");
                return resp;
            }

            logger.info("id = " + req.getId() + "  hotSale = " + req.getHotSale()
                    + " proStatus = " + req.getProStatus());

            ProductInfo model = productInfoService.findById(req.getId());
            model.setHotSale(req.getHotSale());
            model.setProStatus(req.getProStatus());
            if(req.getSequence() != null){
                productInfoService.moveSequence(req.getSequence());
                model.setSequence(req.getSequence());

            }else{
                model.setSequence(null);
            }


            model.setSaleOut(req.getSaleOut());
            model.setUpdateTime(System.currentTimeMillis());
            if(StringHelper.isNotEmpty(req.getTopSaleStr())){
                model.setTopSaleStr(req.getTopSaleStr());
            }else{
                model.setTopSaleStr(null);
            }
            // 根据路由表，对产品进行更新
            productRouteService.updateProduct(model);

            resp.setResult(model);
            resp.setResultCode(StatusCode.SUCCESS.key());
            resp.setMsg("修改成功");
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resp.setMsg("操作异常，请重试");
            resp.setResultCode(StatusCode.EXCEPTION.key());
        }
        return resp;
    }

    /**
     * @param
     * @Title: updateProdFlage
     * @Description: TODO
     */
    @ResponseBody
    @RequestMapping(value = "/updFlag", method = RequestMethod.POST)
    public ResponseBase<ProductInfo> updFlag(
            @RequestBody ProductInfoReq req) {
        ResponseBase<ProductInfo> resp = new ResponseBase<ProductInfo>();


        try {
            if (req == null || req.getId() == null) {
                resp.setResultCode(StatusCode.PARAM_ERROR.key());
                resp.setMsg("参数不对：id is null！");
                return resp;
            }

            logger.info("updFlag id = " + req.getId());

            ProductInfo model = productInfoService.findById(req.getId());

            if(StringHelper.isNotEmpty(req.getLabel01()) ){
                model.setLabel01(req.getLabel01());
                model.setLabel01Color01(req.getLabel01Color01());
                model.setLabel01Color02(req.getLabel01Color02());
                model.setLabel01Color03(req.getLabel01Color03());
            }else{
                model.setLabel01(null);
                model.setLabel01Color01(null);
                model.setLabel01Color02(null);
                model.setLabel01Color03(null);
            }

            if(StringHelper.isNotEmpty(req.getLabel02()) ){
                model.setLabel02(req.getLabel02());
                model.setLabel02Color01(req.getLabel02Color01());
                model.setLabel02Color02(req.getLabel02Color02());
                model.setLabel02Color03(req.getLabel02Color03());
            }else{
                model.setLabel02(null);
                model.setLabel02Color01(null);
                model.setLabel02Color02(null);
                model.setLabel02Color03(null);
            }

            if(StringHelper.isNotEmpty(req.getLabel03()) ){
                model.setLabel03(req.getLabel03());
                model.setLabel03Color01(req.getLabel03Color01());
                model.setLabel03Color02(req.getLabel03Color02());
                model.setLabel03Color03(req.getLabel03Color03());
            }else{
                model.setLabel03(null);
                model.setLabel03Color01(null);
                model.setLabel03Color02(null);
                model.setLabel03Color03(null);
            }

            if(StringHelper.isNotEmpty(req.getLabel04()) ){
                model.setLabel04(req.getLabel04());
                model.setLabel04Color01(req.getLabel04Color01());
                model.setLabel04Color02(req.getLabel04Color02());
                model.setLabel04Color03(req.getLabel04Color03());
            }else{
                model.setLabel04(null);
                model.setLabel04Color01(null);
                model.setLabel04Color02(null);
                model.setLabel04Color03(null);
            }

            if(req.getActBack() != null){
                model.setActBack(req.getActBack());
            }else{
                model.setActBack(null);
            }



            if(StringHelper.isNotEmpty(req.getActFlag())){
                model.setActFlag(req.getActFlag());
            }else{
                model.setActFlag(null);
            }


            if(StringHelper.isNotEmpty(req.getProdFlag01())){
                model.setProdFlag01(req.getProdFlag01());
            }else{
                model.setProdFlag01(null);
            }

            if(StringHelper.isNotEmpty(req.getProdFlag02())){
                model.setProdFlag02(req.getProdFlag02());
            }else{
                model.setProdFlag02(null);
            }

            productInfoService.update(model);

            resp.setResult(model);
            resp.setResultCode(StatusCode.SUCCESS.key());
            resp.setMsg("修改成功");
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resp.setMsg("操作异常，请重试");
            resp.setResultCode(StatusCode.EXCEPTION.key());
        }
        return resp;
    }

    /**
     * @param
     * @Title: deleteProductInfo
     * @Description: TODO
     */
    @ResponseBody
    @RequestMapping(value = "/deleteProductInfo", method = RequestMethod.POST)
    public ResponseBase<ProductInfo> deleteProductInfo(
            @RequestBody ProductInfoReq req) {
        ResponseBase<ProductInfo> resp = new ResponseBase<ProductInfo>();
        try {
            if (req == null || req.getId() == null) {
                resp.setResultCode(StatusCode.PARAM_ERROR.key());
                resp.setMsg("参数不对：id is null！");
                return resp;
            }
            ProductInfo dp = new ProductInfo();
            dp.setId(req.getId());

            // 根据路由表，对产品进行删除
            productRouteService.deleteByProductId(dp.getId());

            resp.setResult(dp);
            resp.setResultCode(StatusCode.SUCCESS.key());
            resp.setMsg("删除成功");
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resp.setMsg("操作异常，请重试");
            resp.setResultCode(StatusCode.EXCEPTION.key());
        }
        return resp;
    }

    /**
     * @param
     * @Title: copy
     * @Description:一键复制功能
     */
    @ResponseBody
    @RequestMapping(value = "/copy", method = RequestMethod.POST)
    public ResponseBase<Boolean> copy(@RequestBody ProductInfoReq req) {
        ResponseBase<Boolean> resp = new ResponseBase<Boolean>();
        try {
            if (req == null || req.getId() == null) {
                resp.setResultCode(StatusCode.PARAM_ERROR.key());
                resp.setMsg("参数不对：id is null！");
                return resp;
            }

            // 根据路由表获得产品信息
            ProductInfo model = productRouteService.getInfoById(req.getId());

            // 设置产品的已募集金额为 0
            model.setYraiseAccount(new BigDecimal(0));

            // 设置产品的剩余额度为募集总量
            model.setSraiseAccount(model.getFinancingAccount());

            // 设置产品的已预约金额为 0
            model.setBespeakAccount(new BigDecimal(0));

            // 设置产品上架状态为未上架
            model.setProStatus(ConstantProduct.PRODUCT_RELEASE_STATE_FALSE);

            // 设置产品热销属性为非热销
            model.setHotSale(ConstantProduct.PRODUCT_HOT_SELLING_FALSE);

            // 设置产品名称为新增
            model.setName("aa" + model.getName() + "—新增");

            // 设置产品编码为空
            model.setProNo(String.valueOf(System.currentTimeMillis()));

            // 设置为未开始起息
            model.setStartDiv(ConstantProduct.PRO_NOT_START_DIV);

            // 设置不自动起息
            model.setAutStartDiv(ConstantProduct.PRO_NO_AUTO_START_DIV);

            // 设置为未开始回款
            model.setPayBackStatus(ConstantProduct.PRODUCT_PAYBACK_STATUS_FALSE);

            //设置是否扣除手续费, 未扣除手续费
            model.setIsPayedFee(ConstantProduct.PRODUCT_PAYED_FEE_FALSE);

            //设置上架時間為空
            model.setStartSaleTime(null);

            //设置下架时间为空
            model.setEndSaleTime(null);

            //设置售罄时间为空
            model.setSaleOutTime(null);

            //设置产品的起息时间为空
            model.setProDividStartDate(null);

            //设置产品的返本付息时间为空
            model.setProDividendDate(null);

            //设置是否满标为否
            model.setSaleOut(0);


            //设置待售为否
            model.setWaitSale(ConstantProduct.PRODUCT_WAITSALE_FALSE);

            // 根据路由表保存产品信息到相应的表中
            Long newProductId = productRouteService.addProduct(model);

            if (newProductId > 0L) {
                resp.setResultCode(StatusCode.SUCCESS.key());
                resp.setMsg("添加成功");
                resp.setResult(true);

                copyProductCanUseCoupons(req.getId(),newProductId);
            } else {
                resp.setMsg("产品编码或者名称已存在,保存失败！产品名称为：" + model.getName());
                resp.setResultCode(StatusCode.EXCEPTION.key());
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resp.setMsg("操作异常，请重试");
            resp.setResultCode(StatusCode.EXCEPTION.key());
        }
        return resp;
    }

    private void copyProductCanUseCoupons(Long fromProductId, Long toProductId) {
        JsonResult result = activityService.copyProductConpons(fromProductId,toProductId);
        logger.info("copy product coupon result :{}",result.msg);
    }

    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    public ResponseBase queryProductList(@RequestBody QueryProductListReq req) {
        List<ProductInfoRes > productResList = new ArrayList<>();
        ResponseBase responseBase = new ResponseBase();

        if (StringUtils.isBlank(req.queryString)) {
            responseBase.setResultCode(ResultCode.PARAM_ERROR.getCode());
            responseBase.setMsg("参数不能为空");
        } else {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("低", "R1");
            paramMap.put("较低", "R2");
            paramMap.put("中", "R3");
            paramMap.put("较高", "R4");
            paramMap.put("高", "R5");

            List<Map<String, Object>> resultList = null;

            String sql = null;
            boolean isTester = this.userRoleService.isTester(req.userId);
            if (paramMap.containsKey(req.queryString)) {
                req.queryString = paramMap.get(req.queryString);
                if (isTester) {
                    sql = "select * from t_product_info where proStatus = 1 and riskLevel = ? and isParent = 0";
                } else {
                    sql = "select * from t_product_info where proStatus = 1 and riskLevel = ? and isTest = 0 and isParent = 0";
                }
                resultList = this.jdbcTemplate.queryForList(sql, new Object[] { req.queryString });
            } else {
                if (isTester) {
                    sql = "select * from t_product_info where proStatus = 1 and (proTermStr = ? or riskLevel = ? or name like ?) and isParent = 0";
                } else {
                    sql = "select * from t_product_info where proStatus = 1 and isTest = 0 and (proTermStr = ? or riskLevel = ? or name like ?) and isParent = 0";
                }
                resultList = this.jdbcTemplate.queryForList(sql, new Object[] {
                        req.queryString, req.queryString, "%" + req.queryString + "%"
                });
            }

            for(Map<String, Object> product :resultList){
                Long productId = Long.valueOf(product.get("id").toString());
                ProductInfoRes productInfoRes = productInfoService.getProductInfoResById(productId);
                productResList.add(productInfoRes);
            }

            responseBase.setResultCode(ResultCode.SUCC.getCode());
            responseBase.setMsg("查询成功");
            responseBase.setResult(productResList);
        }

        return responseBase;
    }

    @ResponseBody
    @RequestMapping(value = "/specialPayback", method = RequestMethod.POST)
    public ResponseBase<ProductInfo> specialPayback(@RequestBody  ProductInfoReq req ) {
        ResponseBase<ProductInfo> resp = new ResponseBase<>();
        if (req == null || req.getId() == null || req.getUserId() == null) {
            resp.setResultCode(StatusCode.PARAM_ERROR.key());
            resp.setMsg("参数不全");
            return resp;
        }

        ProductInfo productInfo = productInfoService.findById(req.getId());
        if(productInfo == null){
            resp.setResultCode(StatusCode.DATA_NOTEXISTS.key());
            resp.setMsg(StatusCode.DATA_NOTEXISTS.desc());
            return resp;
        }

        if(productInfo.getPayBackStatus()!=null && productInfo.getPayBackStatus() == ConstantProduct.PRODUCT_PAYBACK_STATUS_TRUE){
            resp.setResultCode(StatusCode.EXCEPTION.key());
            resp.setMsg("已回款过的产品不能再进行回款");
            return resp;
        }

        HqlFilter hql = new HqlFilter();
        hql.addEQFilter("productId",productInfo.getId());
        hql.addEQFilter("payStatus", ConstantOrderStatus.PAY_STATUS_TRUE);
        List<OrderInfo> list = orderService.findByFilter(hql);
        list.stream().forEach(o ->{
            o.setPayStatus(ConstantOrderStatus.PAY_STATUS_PAYBACK);
            o.setConfirmStatus(ConstantOrderStatus.CONFIRM_STATUS__PAYBACK);
            orderService.update(o);
        });
        productInfoService.addLogRecord(Long.valueOf(productInfo.getId()), Long.valueOf(req.getUserId()));
        productInfo.setPayBackStatus(ConstantProduct.PRODUCT_PAYBACK_STATUS_TRUE);
        productInfoService.update(productInfo);
        resp.setResult(productInfo);

        return resp;

    }

    public void testPayBack (Long productId){

        rabbitTemplate.convertAndSend(POUNDAGE_QUEUE, productId);
        System.out.println("开始回款,请等待");
    }




}